import { defineStore } from 'pinia';

export const useRobotStore = defineStore('robot', {
  state: () => ({
    // 连接相关
    robotIp: '172.10.7.38',
    robotPort: '9090',
    isConnected: false,
    ros: null,
    
    // 运动控制
    moveX: 0,
    moveY: 0,
    rotateX: 0,
    linearSpeed: 0,
    angularSpeed: 0,
    maxLinear: 1.0,
    maxAngular: 2.0,
    
    // 电量状态
    batteryPercentage: 0,
    
    // 传感器数据
    temperature: 0,
    humidity: 0,
    
    // 日志
    logs: [{ text: '系统已启动，请连接机器人...', type: 'info' }]
  }),

  getters: {
    batteryLevelClass: (state) => {
      if (state.batteryPercentage <= 20) return 'critical';
      if (state.batteryPercentage <= 40) return 'low';
      return 'normal';
    },
    
    connectionUrl: (state) => {
      const isHttps = typeof window !== 'undefined' && window.location && window.location.protocol === 'https:';
      const scheme = isHttps ? 'wss' : 'ws';
      return `${scheme}://${state.robotIp}:${state.robotPort}`;
    }
  },

  actions: {
    // 更新机器人IP和端口
    updateRobotConfig(ip, port) {
      this.robotIp = ip;
      this.robotPort = port;
    },

    // 设置连接状态
    setConnectionStatus(status) {
      this.isConnected = status;
    },

    // 设置ROS对象
    setROS(ros) {
      this.ros = ros;
    },

    // 更新运动数据
    updateMovement(x, y, rotate) {
      this.moveX = x;
      this.moveY = y;
      this.rotateX = rotate;
    },

    // 更新速度
    updateSpeed(linear, angular) {
      this.linearSpeed = linear;
      this.angularSpeed = angular;
    },

    // 更新电量
    updateBattery(percentage) {
      this.batteryPercentage = Math.max(0, Math.min(100, Math.round(percentage)));
    },

    // 更新传感器数据
    updateSensorData(temperature, humidity) {
      this.temperature = temperature;
      this.humidity = humidity;
    },

    // 添加日志
    addLog(msg, type = 'info') {
      const timestamp = new Date().toLocaleTimeString();
      this.logs.push({ text: `[${timestamp}] ${msg}`, type });
      if (this.logs.length > 100) this.logs.shift();
    },

    // 清空日志
    clearLogs() {
      this.logs = [];
    }
  }
});
